package com.huwaiwai001.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author 歪大哥😁
 * @date 2020-07-07.
 */
public class NIOServer {


    public static void main(String[] args) throws Exception {
        // 创建一个serverSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 得到一个selector
        Selector selector = Selector.open();
        // 监听6666端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 注册到selector  并且关心OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);


        while (true) {
            if (selector.select(1000L) == 0) {
                System.out.println("服务器等待1秒  无连接");
                continue;
            }
            // 返回 >0 表示获取到关注事件 则获取事件发生的selectedKeys
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            // 使用迭代器遍历

            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();
                if (key.isAcceptable()) {
                    // 获取一个socketChannel 注册到selector中 关注read事件 并且分配一个buffer
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {
                    // 获取注册的socketChannel
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    // 获取分配的 buffer
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    // 将数据读取到buffer中
                    socketChannel.read(byteBuffer);
                    System.out.println(new String(byteBuffer.array()));
                    key.cancel();
                }
                // 移除当前 事件
                keyIterator.remove();
            }
        }
    }
}
